package com.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.service.DroneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @className: MessageWebSocketHandler
 * @description: TODO 类描述
 * @author: Kuangkeli
 * @date: 2024/07/02 22:19
 *  **/
@Component
public class MessageWebSocketHandler extends TextWebSocketHandler {
    @Autowired DroneService droneService;
    private final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessions.add(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session);
    }

    public void sendMessage(String message) {
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String payload = message.getPayload();
        System.out.println("Received message: " + payload);
        JSONObject jsonObject = JSON.parseObject(payload);

        // 提取值
        int x = jsonObject.getIntValue("x");
        int y = jsonObject.getIntValue("y");
        int z = jsonObject.getIntValue("z");
        int r = jsonObject.getIntValue("r");

        droneService.remoteControl(x, y, z, r);
    }
}
